import { Component, OnInit, OnDestroy } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged';

import { TableTab, TableHeader } from "../f10-shared/interface-shared";
import { scroll } from "../f10-shared/common-methods";
import { removeHMS, compare, SHnumAndPriceColors } from "../f10-shared/util";
import { F10Service } from "../service/f10.service";
import { ScrollService } from "../service/scroll.service";

// interface
import { ShareholderNum } from "./shareholder.interface"

@Component({
  templateUrl: 'shareholder.component.html',
  styleUrls: ['shareholder.component.less']
})
export class ShareholderComponent implements OnInit {
  timer = null;
  tabClicked = {
    flag: false
  };
  activeTabIndex = 0;
  scrollTimer = null;
  mustChange = false;
  // 小标题列表
  subLists: TableTab[] = [
    {
      label: "股东人数",
      class: 'sub-title-0'
    },
    {
      label: "十大股东",
      class: 'sub-title-1'
    },
    {
      label: "十大流通股东",
      class: 'sub-title-2'
    },
    // {
    //   label: "机构持股情况",
    //   class: 'sub-title-3'
    // }
  ]
  // 股票代码Observable
  routerParamsStream: Observable<any>;
  // 股东人数
  shareholderNum: Observable<any>;
  shareholderNumHeader: TableHeader[] = [
    {
      format: false,
      label: `指标\\日期`,
      key: 'endDate'
    },
    // {
    //   format: false,
    //   label: `股价(元)`,
    //   key: 'price'
    // },
    {
      format: true,
      label: `股东总户数(户)`,
      key: 'SHNum'
    },
    {
      format: true,
      label: `户均持股数(股)`,
      key: 'averageHoldSum'
    },
    // {
    //   format: true,
    //   label: `户均持股比例(%)`,
    //   key: 'holdProportionPAccount'
    // },
    // {
    //   format: true,
    //   label: `相对上一期报告期户均持股比例变化(百分点)`,
    //   key: 'proportionChange'
    // }
  ]
  // 股东人数与股价联动
  SHNumAndPrice: Observable<any>;
  // 10大股东
  top10TimeSet = new Set();
  top10Shareholder: Observable<any>;
  top10ShareholderChart: Observable<any>;
  top10ShareholderTab: Observable<any>;
  top10ShareholderHeader: TableHeader[] = [
    {
      label: '名次',
      key: 'SHNo'
    },
    {
      label: '股东名称',
      key: 'SHList'
    },
    {
      label: '股东性质',
      key: 'SHKind'
    },
    {
      label: '股份类型',
      key: 'shareCharacterStatement'
    },
    {
      format: true,
      label: '持股数(股)',
      key: 'holdSum'
    },
    {
      format: true,
      label: '占总股本比例(%)',
      key: 'PCTOfTotalShares'
    },
    {
      format: true,
      label: '增减变动(股)',
      key: 'holdSumChange'
    },
  ]

  // 10大流通股东
  top10FloatTimeSet = new Set()
  top10FloatShareholder: Observable<any>;
  top10FloatShareholderChart: Observable<any>;
  top10FloatShareholderTab: Observable<any>;

  // 10大股东与10大流通股东统计
  top10ShareholderCount: Observable<any>;
  top10FloatShareholderCount: Observable<any>;
  
  top10ShareHolderEmitter = new BehaviorSubject('')
  top10ShareHolderChartEmitter = new BehaviorSubject('')
  top10FloatShareHolderEmitter = new BehaviorSubject('')
  top10FloatShareHolderChartEmitter = new BehaviorSubject('')
  constructor (
    private router: ActivatedRoute,
    private f10Service: F10Service,
    private scrollService: ScrollService
  ) {}

  ngOnInit () {
    this.routerParamsStream = this.router.parent.parent.params.map(params => params["id"]).filter(id => !!id).map(id => {
      let stock = {
        symbol: (<string>id).replace("_", ".")
      };
      return stock
    })
    .do(data => console.log('%c 股票代码 =======>>>>>>>', 'color: #0f0', data.symbol))
    // 股东人数
    this.shareholderNum = this.routerParamsStream.switchMap(stock => this.f10Service.getShareholdernum(stock.symbol))
      .map((data) => 
        data.map( (d: any) =>
          ({
            ...d,
            endDate: removeHMS(d.endDate)
            // proportionChange: d.proportionChange && d.proportionChange.toFixed(2)
          })
        ).sort(compare('endDate', 'des'))
      )
      .do(data => console.log('股东人数', data))
      .publish().refCount()

    // 股东人数与股价联动
    this.SHNumAndPrice = this.shareholderNum
      .map(data => [...data].reverse())  // => 绘图要求日期从旧到新
      .map(data => {
        let SHNum = []
        let price = []
        let endDate = []
        data.forEach(d => {
          SHNum = [...SHNum, parseFloat(d.SHNum)]
          price = [...price, parseFloat(d.price)]
          endDate = [...endDate, d.endDate]
        })
        return {
          type: 'bar',
          data: {
            labels: [...endDate],
            datasets: [
              // {
              //   type: 'line',
              //   label: '股价(元)',
              //   backgroundColor: SHnumAndPriceColors.orange,
              //   borderColor: SHnumAndPriceColors.orange,
              //   borderWidth: 2,
              //   fill: false,
              //   data: [...price],
              //   yAxisID: "y-axis-2",
              // },
              {
                type: 'bar',
                label: '股东人数(户)',
                backgroundColor: SHnumAndPriceColors.blue,
                borderColor: SHnumAndPriceColors.blue,
                borderWidth: 0,
                data: [...SHNum],
                yAxisID: "y-axis-1",
              }
            ]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
              display: true,
              text: '股东人数',
              // text: '股东人数与股价联动',
              padding: 7
            },
            tooltips: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              yAxes: [
                {
                  type: "linear",
                  display: true,
                  position: "left",
                  id: "y-axis-1",
                },
                // {
                //   type: "linear", 
                //   display: true,
                //   position: "right",
                //   id: "y-axis-2",
                //   gridLines: {
                //     drawOnChartArea: false,
                //   },
                // }
              ],
            }
          }
        }
      })

    // 十大股东
    let top10ShareholderStream = this.routerParamsStream.switchMap(stock => this.f10Service.getTop10shareholders(stock.symbol))
      .map((data) => {
        data.holders = data.holders.map(d => {
          return {
            ...d,
            endDate: removeHMS(d.endDate)
          }
        })
        data.floatHolders = data.floatHolders.map(d => {
          return {
            ...d,
            endDate: removeHMS(d.endDate)
          }
        })
        return data
      })
      .do(data => console.log('%c 十大股东数据====》》》》》', 'color: #0f0', data))
      .publish().refCount();

    this.top10ShareholderTab = top10ShareholderStream
      .do(data => this.top10TimeSet.clear())
      .map(data => {
        let newData = []
        data.holders.forEach(d => {
          if (!this.top10TimeSet.has(d.endDate)) {
            this.top10TimeSet.add(d.endDate)
            newData = [...newData, {
              label: d.endDate,
              class: d.endDate
            }]
          }
        })
        newData = newData.sort(compare('label', 'des'))
        if (newData.length > 0) {
          this.top10ShareHolderToggle(newData[0].label)
          this.top10ShareHolderChartToggle(newData[0].label)
        }
        return newData
      }).publish().refCount();
      
    this.top10Shareholder = top10ShareholderStream
      .map(data => data.holders)
      .switchMap(data => {
        return this.top10ShareHolderEmitter
        .map(time => data.filter(d => d.endDate === time).sort(compare('SHNo')).slice(0, 10))
        // .do(data => console.log('top10Shareholder =>', data))
      });

    this.top10ShareholderChart = top10ShareholderStream
      .map(data => data.holders)
      .switchMap(data => {
        return this.top10ShareHolderChartEmitter
        .map(time => data.filter(d => d.endDate === time).sort(compare('SHNo')).slice(0, 10))
        // .do(data => console.log('=====>>>> 左侧十大股东图形数据', data))
      });

    this.top10ShareholderCount = this.top10Shareholder
      .switchMap(data => {
        return this.top10ShareHolderEmitter
          .map(time => (
            data.reduce((accu, curr) => ({
              amount: accu.amount + curr.holdSum,
              ratio: accu.ratio + curr.PCTOfTotalShares
            }) , {amount: 0, ratio: 0})
          ))
      })
      .map(data => ({
        amount: Math.floor(data.amount / 10000),
        ratio: data.ratio.toFixed(2) + '%'
      }))

    this.top10FloatShareholderTab = top10ShareholderStream
      .do(data => this.top10FloatTimeSet.clear())
      .map(data => {
        let newData = []
        data.floatHolders.forEach(d => {
          if (!this.top10FloatTimeSet.has(d.endDate)) {
            this.top10FloatTimeSet.add(d.endDate)
            newData = [...newData, {
              label: d.endDate,
              class: d.endDate
            }]
          }
        })
        newData = newData.sort(compare('label', 'des'))
        if (newData.length > 0) {
          this.top10FloatShareHolderToggle(newData[0].label)
          this.top10FloatShareHolderChartToggle(newData[0].label)
        }
        return newData
      }).publish().refCount();

    this.top10FloatShareholder = top10ShareholderStream
      .map(data => data.floatHolders)
      .switchMap(data => {
        return this.top10FloatShareHolderEmitter
        .map(time => data.filter(d => d.endDate === time).sort(compare('SHNo')).slice(0, 10))
      })
      // .do(data => console.log('十大流通股东===>>>', data))

    this.top10FloatShareholderChart = top10ShareholderStream
      .map(data => data.floatHolders)
      .switchMap(data => {
        return this.top10FloatShareHolderChartEmitter
        .map(time => data.filter(d => d.endDate === time).sort(compare('SHNo')).slice(0, 10))
      })

    this.top10FloatShareholderCount = this.top10FloatShareholder
      .switchMap(data => {
        return this.top10FloatShareHolderEmitter
          .map(time => (
            data.reduce((accu, curr) => ({
              amount: accu.amount + curr.holdSum,
              ratio: accu.ratio + curr.PCTOfTotalShares
            }) , {amount: 0, ratio: 0})
          ))
      })
      .map(data => ({
        amount: Math.floor(data.amount / 10000),
        ratio: data.ratio.toFixed(2) + '%'
      }))
    
  }

  tabToggle (event) {
    this.tabClicked.flag = true
    this.timer = scroll(`segment-container`, event, this.timer, this.tabClicked);
  }

  scrollEvent (e, el, el1, el2, el3, el4, el5) {
    if (this.scrollTimer) clearTimeout(this.scrollTimer)
    this.scrollTimer = setTimeout(() => {
      this.mustChange = !this.mustChange
      this.tabClicked.flag = false
      this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
    }, 50)
    if (this.tabClicked.flag) return
    this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
  }

  // 不同日期10大股东切换
  top10ShareHolderToggle (event) {
    this.top10ShareHolderEmitter.next(event)
  }

  top10ShareHolderChartToggle (event) {
    this.top10ShareHolderChartEmitter.next(event)
  }

  // 不同日期10大流通股东切换
  top10FloatShareHolderToggle (event) {
    this.top10FloatShareHolderEmitter.next(event)
  }

  top10FloatShareHolderChartToggle (event) {
    this.top10FloatShareHolderChartEmitter.next(event)
  }
}